<?php
/*
 * This file aimed to pass command wich do not return anything special except true or false
 * Record, Pause, Resume, Cancel are in this case.
 */
require_once("../../config.php");
require_once("myLib.php");
global $CFG, $COURSE, $USER;
$reason = "";

//Paramètres
$Ginstid = optional_param('instid', null, PARAM_INT);
$Guuid = optional_param('uuid', null, PARAM_SAFEDIR);
$Gcam = optional_param('cam', null, PARAM_ALPHAEXT);
$Gcmd = optional_param('cmd', null, PARAM_ALPHA);

//Permission
if(isset($Ginstid)){
    if(is_allowed('mod/podcast:edit', $COURSE->id, $Ginstid)){
        if(isset($Gcam) && isset($Gcmd)){
            $command1 = "ssh -i ".$CFG->podcast_path2rsakey." ".$CFG->podcast_username."@".$CFG->podcast_path2pcp." pcast --server ".$CFG->podcast_path2pcp." --user ".$CFG->podcast_username." --pass ".$CFG->podcast_password." --".$_GET['cmd']." \\'".$_GET['cam']."\\'";
            $response =  exec($command1, $output, $return);
            if($return != 0){
                $reason = getError($return);
                if($return == 36){//L'erreur 36 nous renseigne que la requete a échoué, en fait c'est qu'on annule / et en pause en enregistremnt non démarré, que l'on reprend un enregistrement non mis en pause... rien de grave.
                    $success = "SUCCESS";
                }else{
                    $success = "FAILURE";
                }
            }else if($return == 0){
                $success = "SUCCESS";
            }
            if($Gcmd === "cancel"){//En cas d'abandon, il nous faut libérer la caméra.
                if(delete_records("podcast_cameras", "uuid", strval($Guuid), "user", strval($USER->id))){
                    $success = "SUCCESS";
                }else{
                    $success = "FAILURE";
                }
            }
        }else{
            $reason = 'Not Enough Args';
            $success = "FAILURE";
        }
    }else{
        $reason = 'Permission denied';
        $success = "FAILURE";
    }
}else{
    $reason = 'Permission denied';
    $success = "FAILURE";
}

header('Content-Type: text/xml; charset=UTF-8');
//On rend compte au client du succès ou de l'échec de l'opération.
$doc = new DOMDocument('1.0', 'utf-8');
$message = $doc->createElement( "message" );
$doc->appendChild( $message );
$xmlRespSucc = $doc->createElement( "success" );
$xmlRespSuccWhy = $doc->createElement( "reason" );
$xmlRespCameraName = $doc->createElement( "cameraName" );
$xmlRespCameraUuid = $doc->createElement( "cameraUuid" );
$xmlRespCameraName->appendChild( $doc->createTextNode( $Gcam ));
$xmlRespCameraUuid->appendChild( $doc->createTextNode( $Guuid ));
$xmlRespSucc->appendChild( $doc->createTextNode( $success ));
$xmlRespSuccWhy->appendChild( $doc->createTextNode( $reason ));
$message->appendChild( $xmlRespSucc );
$message->appendChild( $xmlRespSuccWhy );
$message->appendChild( $xmlRespCameraName );
$message->appendChild( $xmlRespCameraUuid );
echo $doc->saveXML();
?>